<?php
namespace Modules\Stats\Http\Controllers\Admin\V1;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

use Modules\Stats\Entities\UserStats;
use Modules\User\Entities\User;

use Setting;
use Validator;
use ThrowException;
use DB;

class UserStatsController extends Controller
{
    public function index(Request $req)
    {
        $rule = [
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest(); 

        $options = $req->all();

        $userInfoOnly = [
            'id',
            'uuid',
            'headimg',
            'name',
            'phone'
        ];

        // 所有统计字段
        $allKey = [
            'all_get_money_price',
            'all_get_score_price',
            'all_pay_money_price',
            'all_pay_score_price',
            'box_get_money_price',
            'box_get_score_price',
            'box_pay_money_price',
            'box_pay_score_price',
            'fudai_get_money_price',
            'fudai_get_score_price',
            'fudai_pay_money_price',
            'fudai_pay_score_price',
            'yfs_get_money_price',
            'yfs_get_score_price',
            'yfs_pay_money_price',
            'yfs_pay_score_price',
        ];

        // 没有指定日期或者两个日期是同一天
        if ((!$req->input('min_day') && !$req->input('max_day')) 
            || ($req->input('min_day') == $req->input('max_day'))) {

            $options['with'] = ['user'];
            $builder = UserStats::whereHas('user');

            if ($req->input('min_day')) {
                // 筛选日期
                $builder = $builder->where('day', $req->input('min_day'));
            }
            else {
                // 无日期筛选,即显示累计
                $builder = $builder->whereNull('day');
            }

            $options['builder'] = $builder;

            $options['only'] = array_merge([
                'id',
                'uuid',
                'user' => [
                    'id',
                    'uuid',
                    'headimg',
                    'name',
                    'phone'
                ],
            ], $allKey);

            $list = UserStats::getList($options);
            return $list->generateListResponse();
        }


        $dayStart = $req->input('min_day') ?: '2000-10-10';
        $dayEnd = $req->input('max_day') ?: '2200-10-10';

        $perPage = $req->input('per_page') ?: 10;
        $page = $req->input('page') ?: 1;

        // 所有选择字段
        $allSelectField = array_map(function ($key) {
            return DB::raw('SUM(' . $key . ') as ' . $key);
        }, $allKey);
        array_push($allSelectField, 'user_id');

        $builder = UserStats::search($req->input('key'))->where('day', '<=', $dayEnd)->where('day', '>=', $dayStart);
        $itemTotal = UserStats::search($req->input('key'))->where('day', '<=', $dayEnd)->where('day', '>=', $dayStart)->count(DB::raw('DISTINCT(user_id)'));

        $orderBy = explode('-', $req->input('sort_by') ?: 'all_pay_money_price-desc');
        $list = $builder->select($allSelectField)->groupBy('user_id')->skip(($page - 1) * $perPage)->take($perPage)->orderBy($orderBy[0], $orderBy[1])->get();

        $userIds = $list->pluck('user_id');
        $users = User::whereIn('id', $userIds)->get();
        $list->each(function ($item) use ($users, $userInfoOnly) {
            $item['user'] = $users->where('id', $item->user_id)->first()->getInfo($userInfoOnly);
        });

        return [
            'list' => $list,
            'item_total' => $itemTotal
        ];
    }
}
